<script lang="ts">
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userAPI } from '@/api'

export default defineComponent({
  name: "userProfile",
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const profileFormRef = ref<HTMLElement>()
    const saving = ref(false)
    const uploading = ref(false)

    // 表单数据
    const profileForm = reactive<{
      nickname: string
      avatar: string
      gender: string
      birth_date: string
      height: number | null
      weight: number | null
      fitness_goal: string
      fitness_level: string
      dietary_preference: string
      activity_level: string
      has_diabetes: boolean
      has_hypertension: boolean
      has_heart_disease: boolean
      food_allergies: string
      dietary_restrictions: string
      preferred_workout_duration: number
      preferred_workout_times: number
    }>({
      nickname: '',
      avatar: '',
      gender: '',
      birth_date: '',
      height: null,
      weight: null,
      fitness_goal: 'keep_fit',
      fitness_level: 'beginner',
      dietary_preference: 'regular',
      activity_level: 'sedentary',
      has_diabetes: false,
      has_hypertension: false,
      has_heart_disease: false,
      food_allergies: '',
      dietary_restrictions: '',
      preferred_workout_duration: 30,
      preferred_workout_times: 3
    })

    // 表单验证规则
    const rules = {
      nickname: [
        { max: 50, message: '昵称不能超过50个字符', trigger: 'blur' }
      ],
      height: [
        { type: 'number', min: 50, max: 250, message: '身高必须在50-250厘米之间', trigger: 'blur' }
      ],
      weight: [
        { type: 'number', min: 20, max: 300, message: '体重必须在20-300千克之间', trigger: 'blur' }
      ]
    }

    // 计算属性
    const bmiValue = computed(() => {
      if (profileForm.height && profileForm.weight) {
        const heightInM = profileForm.height / 100
        return ((profileForm.weight / (heightInM * heightInM))).toFixed(1)
      }
      return null
    })

    const bmiCategoryText = computed(() => {
      const bmi = parseFloat(bmiValue.value)
      if (!bmi) return ''
      if (bmi < 18.5) return '偏瘦'
      if (bmi < 25) return '正常'
      if (bmi < 30) return '超重'
      return '肥胖'
    })

    const bmiTagType = computed(() => {
      const bmi = parseFloat(bmiValue.value)
      if (!bmi) return 'info'
      if (bmi < 18.5) return 'warning'
      if (bmi < 25) return 'success'
      if (bmi < 30) return 'warning'
      return 'danger'
    })

    const showNutritionInfo = computed(() => {
      return profileForm.height && profileForm.weight && profileForm.gender && profileForm.birth_date
    })

    const bmrValue = computed(() => {
      if (!showNutritionInfo.value) return null
      // 简化的BMR计算
      const age = new Date().getFullYear() - new Date(profileForm.birth_date).getFullYear()
      if (profileForm.gender === 'M') {
        return Math.round(10 * profileForm.weight + 6.25 * profileForm.height - 5 * age + 5)
      } else {
        return Math.round(10 * profileForm.weight + 6.25 * profileForm.height - 5 * age - 161)
      }
    })

    const tdeeValue = computed(() => {
      if (!bmrValue.value) return null
      const multipliers = {
        sedentary: 1.2,
        light: 1.375,
        moderate: 1.55,
        active: 1.725,
        very_active: 1.9
      }
      return Math.round(bmrValue.value * multipliers[profileForm.activity_level])
    })

    const calorieTarget = computed(() => {
      if (!tdeeValue.value) return null
      if (profileForm.fitness_goal === 'weight_loss') {
        return tdeeValue.value - 500
      } else if (profileForm.fitness_goal === 'muscle_gain') {
        return tdeeValue.value + 300
      }
      return tdeeValue.value
    })

    // 判断是否从详情页跳转过来的计算属性
    const isFromDetail = computed(() => {
      return route.query.from === 'detail'
    })

    // 头像上传前验证
    const beforeAvatarUpload = (file: File): boolean => {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 上传到七牛云
    const uploadToQiniu = async (options: { file: File }) => {
      console.log('开始上传头像，文件信息:', options.file)
      uploading.value = true
      try {
        // 这里需要调用后端API获取七牛云上传token
        console.log('正在获取七牛云上传token...')
        const response = await userAPI.getQiniuToken()
        console.log('获取token响应:', response)
        
        if (response.success) {
          console.log('成功获取token，开始上传到七牛云')
          const formData = new FormData()
          formData.append('file', options.file)
          formData.append('token', response.data.token)
          formData.append('key', response.data.key) // 使用后端返回的key

          console.log('上传参数:', {
            fileName: options.file.name,
            fileSize: options.file.size,
            key: response.data.key,
            tokenLength: response.data.token.length
          })

          const uploadResponse = await fetch('https://upload-z1.qiniup.com/', {
            method: 'POST',
            body: formData
          })

          console.log('七牛云上传响应状态:', uploadResponse.status, uploadResponse.statusText)

          if (!uploadResponse.ok) {
            const errorText = await uploadResponse.text()
            console.error('七牛云上传失败详情:', errorText)
            throw new Error(`上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`)
          }

          const result = await uploadResponse.json()
          console.log('七牛云上传结果:', result)
          
          if (result.key) {
            // 对于私有空间，需要获取下载token
            try {
              console.log('获取下载token，key:', result.key)
              const downloadResponse = await userAPI.getQiniuDownloadToken(result.key)
              console.log('下载token响应:', downloadResponse)
              
              if (downloadResponse.success) {
                profileForm.avatar = downloadResponse.data.download_url
                console.log('使用私有下载URL:', profileForm.avatar)
              } else {
                // 如果获取下载token失败，使用基础URL
                profileForm.avatar = `${response.data.domain}/${result.key}`
                console.log('使用基础URL:', profileForm.avatar)
              }
            } catch (error) {
              // 如果获取下载token失败，使用基础URL
              profileForm.avatar = `${response.data.domain}/${result.key}`
              console.warn('获取下载token失败，使用基础URL:', error)
              console.log('最终使用URL:', profileForm.avatar)
            }
            ElMessage.success('头像上传成功')
          } else {
            throw new Error('上传结果中没有返回key')
          }
        } else {
          throw new Error(response.message || '获取上传token失败')
        }
      } catch (error) {
        ElMessage.error('头像上传失败')
        console.error('Upload error:', error)
      } finally {
        uploading.value = false
      }
    }

    // 加载用户资料
    const loadProfile = async () => {
      try {
        const response = await userAPI.getUserProfile()
        console.log('获取用户资料响应:', response)
        
        if (response.success) {
          // 处理数据类型转换，确保数字字段正确
          const data = { ...response.data }
          
          // 转换数字字段，确保不为null
          if (data.height !== null && data.height !== undefined) {
            data.height = Number(data.height)
            console.log('身高数据转换:', data.height, typeof data.height)
          } else {
            data.height = null
            console.log('身高数据为null，设置为null')
          }
          
          if (data.weight !== null && data.weight !== undefined) {
            data.weight = Number(data.weight)
            console.log('体重数据转换:', data.weight, typeof data.weight)
          } else {
            data.weight = null
            console.log('体重数据为null，设置为null')
          }
          
          if (data.preferred_workout_duration !== null && data.preferred_workout_duration !== undefined) {
            data.preferred_workout_duration = Number(data.preferred_workout_duration)
          }
          if (data.preferred_workout_times !== null && data.preferred_workout_times !== undefined) {
            data.preferred_workout_times = Number(data.preferred_workout_times)
          }
          
          Object.assign(profileForm, data)
          console.log('加载后的表单数据:', profileForm)
          console.log('身高字段状态:', profileForm.height, typeof profileForm.height)
          console.log('体重字段状态:', profileForm.weight, typeof profileForm.weight)
          
          // 如果有头像URL，需要获取下载token
          if (profileForm.avatar && (profileForm.avatar.includes('tldldmtpy.hb-bkt.clouddn.com') || profileForm.avatar.includes('t1cfb88a9.hb-bkt.clouddn.com'))) {
            try {
              // 从avatar URL中提取key
              const urlParts = profileForm.avatar.split('/')
              const key = urlParts[urlParts.length - 1]
              console.log('从头像URL提取的key:', key)
              
              const downloadResponse = await userAPI.getQiniuDownloadToken(key)
              console.log('获取下载token响应:', downloadResponse)
              
              if (downloadResponse.success) {
                profileForm.avatar = downloadResponse.data.download_url
                console.log('使用下载tokenURL:', profileForm.avatar)
              } else {
                console.warn('获取下载token失败，保持原始URL:', profileForm.avatar)
              }
            } catch (error) {
              console.warn('获取头像下载token失败，保持原始URL:', error)
              // 保持原始URL，不修改profileForm.avatar
            }
          }
        }
      } catch (error) {
        ElMessage.error('加载用户资料失败')
        console.error('Load profile error:', error)
      }
    }

    // 保存用户资料
    const saveProfile = async () => {
      try {
        console.log('[保存用户资料] 开始验证表单')
        await profileFormRef.value.validate()
        console.log('[保存用户资料] 表单验证通过')
        
        saving.value = true
        console.log('[保存用户资料] 准备发送数据:', profileForm)
        
        const response = await userAPI.updateUserProfile(profileForm)
        console.log('[保存用户资料] API响应:', response)
        
        if (response.success) {
          ElMessage.success('资料保存成功')
          console.log('[保存用户资料] 保存成功')
          
          // 如果是从详情页跳转过来的，保存成功后返回详情页
          if (isFromDetail.value) {
            router.push('/user-profile-one')
          }
        } else {
          ElMessage.error(response.message || '保存失败')
          console.error('[保存用户资料] 保存失败:', response.message)
        }
      } catch (error) {
        console.error('[保存用户资料] 发生异常:', error)
        console.error('[保存用户资料] 异常详情:', {
          message: error.message,
          response: error.response,
          status: error.response?.status,
          data: error.response?.data
        })
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    // 处理图片加载错误
    const handleImageError = (event: Event) => {
      const img = event.target as HTMLImageElement
      console.error('头像图片加载失败:', img.src)
      console.log('尝试重新获取下载token...')
      
      // 如果图片加载失败，尝试重新获取下载token
      if (img.src.includes('tldldmtpy.hb-bkt.clouddn.com') || img.src.includes('t1cfb88a9.hb-bkt.clouddn.com')) {
        // 正确提取key，去掉URL参数
        let key = ''
        if (img.src.includes('?')) {
          // 如果有URL参数，提取问号前的部分
          const urlWithoutParams = img.src.split('?')[0]
          const urlParts = urlWithoutParams.split('/')
          key = urlParts[urlParts.length - 1]
        } else {
          // 如果没有URL参数，直接提取最后一部分
          const urlParts = img.src.split('/')
          key = urlParts[urlParts.length - 1]
        }
        console.log('从失败URL提取key:', key)
        
        userAPI.getQiniuDownloadToken(key).then(response => {
          if (response.success) {
            profileForm.avatar = response.data.download_url
            console.log('重新获取下载token成功:', profileForm.avatar)
          } else {
            console.error('重新获取下载token失败:', response.message)
          }
        }).catch(error => {
          console.error('重新获取下载token异常:', error)
        })
      }
    }

    // 重置表单
    const resetForm = () => {
      ElMessageBox.confirm('确定要重置所有资料吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        profileFormRef.value.resetFields()
        loadProfile()
        ElMessage.success('表单已重置')
      })
    }

    // 测试输入框编辑功能
    const testInputEdit = () => {
      console.log('测试输入框编辑功能')
      console.log('当前身高值:', profileForm.height)
      console.log('当前体重值:', profileForm.weight)
      
      // 手动设置一些测试值
      profileForm.height = 175
      profileForm.weight = 70
      
      console.log('设置后的身高值:', profileForm.height)
      console.log('设置后的体重值:', profileForm.weight)
      
      ElMessage.success('已设置测试值，请检查输入框是否可编辑')
    }

    // 返回详情页
    const handleBack = () => {
      router.push('/user-profile-one')
    }

    onMounted(() => {
      loadProfile()
    })

         return {
       profileFormRef,
       profileForm,
       rules,
       saving,
       uploading,
       bmiValue,
       bmiCategoryText,
       bmiTagType,
       showNutritionInfo,
       bmrValue,
       tdeeValue,
               calorieTarget,
        isFromDetail,
        beforeAvatarUpload,
        uploadToQiniu,
        handleImageError,
        saveProfile,
        resetForm,
        testInputEdit,
        handleBack
     }
  }
})
</script>

<template>
  <div class="user-profile-container">
    <div class="profile-header">
      <h1>{{ isFromDetail ? '编辑个人资料' : '个人资料设置' }}</h1>
      <p>{{ isFromDetail ? '修改您的个人信息，保存后返回详情页' : '完善您的个人信息，获得更精准的健身建议' }}</p>
    </div>

    <div class="profile-content">
      <el-form 
        :model="profileForm" 
        :rules="rules" 
        ref="profileFormRef" 
        label-width="120px"
        class="profile-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          
          <!-- 头像上传 -->
          <el-form-item label="头像" prop="avatar">
            <div class="avatar-upload">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadToQiniu"
              >
                                 <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" @error="handleImageError" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">点击上传头像，支持JPG、PNG格式</div>
            </div>
          </el-form-item>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender">
              <el-radio label="M">男</el-radio>
              <el-radio label="F">女</el-radio>
              <el-radio label="O">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="出生日期" prop="birth_date">
            <el-date-picker
              v-model="profileForm.birth_date"
              type="date"
              placeholder="选择出生日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>

        <!-- 身体指标 -->
        <div class="form-section">
          <h3>身体指标</h3>
          
          <el-form-item label="身高" prop="height">
            <el-input-number
              v-model="profileForm.height"
              :min="50"
              :max="250"
              :precision="1"
              placeholder="厘米"
              :disabled="false"
              :readonly="false"
              style="width: 200px;"
            />
            <span class="unit">厘米</span>
          </el-form-item>

          <el-form-item label="体重" prop="weight">
            <el-input-number
              v-model="profileForm.weight"
              :min="20"
              :max="300"
              :precision="1"
              placeholder="千克"
              :disabled="false"
              :readonly="false"
              style="width: 200px;"
            />
            <span class="unit">千克</span>
          </el-form-item>

          <!-- BMI显示 -->
          <el-form-item label="BMI指数" v-if="bmiValue">
            <div class="bmi-display">
              <span class="bmi-value">{{ bmiValue }}</span>
              <el-tag :type="bmiTagType" size="small">{{ bmiCategoryText }}</el-tag>
            </div>
          </el-form-item>
        </div>

        <!-- 健身目标 -->
        <div class="form-section">
          <h3>健身目标</h3>
          
          <el-form-item label="健身目标" prop="fitness_goal">
            <el-select v-model="profileForm.fitness_goal" placeholder="选择健身目标">
              <el-option label="减脂" value="weight_loss" />
              <el-option label="增肌" value="muscle_gain" />
              <el-option label="保持健康" value="keep_fit" />
              <el-option label="提升耐力" value="endurance" />
            </el-select>
          </el-form-item>

          <el-form-item label="健身水平" prop="fitness_level">
            <el-select v-model="profileForm.fitness_level" placeholder="选择健身水平">
              <el-option label="新手" value="beginner" />
              <el-option label="进阶" value="intermediate" />
              <el-option label="专业" value="advanced" />
            </el-select>
          </el-form-item>

          <el-form-item label="活动水平" prop="activity_level">
            <el-select v-model="profileForm.activity_level" placeholder="选择活动水平">
              <el-option label="久坐(几乎不运动)" value="sedentary" />
              <el-option label="轻度活动(每周1-3天运动)" value="light" />
              <el-option label="中度活动(每周3-5天运动)" value="moderate" />
              <el-option label="积极活动(每周6-7天运动)" value="active" />
              <el-option label="非常活跃(高强度训练或体力工作)" value="very_active" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 饮食偏好 -->
        <div class="form-section">
          <h3>饮食偏好</h3>
          
          <el-form-item label="饮食偏好" prop="dietary_preference">
            <el-select v-model="profileForm.dietary_preference" placeholder="选择饮食偏好">
              <el-option label="普通" value="regular" />
              <el-option label="素食" value="vegetarian" />
              <el-option label="纯素" value="vegan" />
              <el-option label="低碳水" value="low_carb" />
              <el-option label="生酮" value="keto" />
              <el-option label="无麸质" value="gluten_free" />
              <el-option label="无乳糖" value="lactose_free" />
            </el-select>
          </el-form-item>

          <el-form-item label="食物过敏" prop="food_allergies">
            <el-input
              v-model="profileForm.food_allergies"
              type="textarea"
              :rows="3"
              placeholder="请描述您的食物过敏情况"
            />
          </el-form-item>

          <el-form-item label="其他饮食限制" prop="dietary_restrictions">
            <el-input
              v-model="profileForm.dietary_restrictions"
              type="textarea"
              :rows="3"
              placeholder="请描述其他饮食限制"
            />
          </el-form-item>
        </div>

        <!-- 健身偏好 -->
        <div class="form-section">
          <h3>健身偏好</h3>
          
          <el-form-item label="单次训练时长" prop="preferred_workout_duration">
            <el-input-number
              v-model="profileForm.preferred_workout_duration"
              :min="10"
              :max="180"
              :step="5"
            />
            <span class="unit">分钟</span>
          </el-form-item>

          <el-form-item label="每周训练次数" prop="preferred_workout_times">
            <el-input-number
              v-model="profileForm.preferred_workout_times"
              :min="1"
              :max="7"
            />
            <span class="unit">次/周</span>
          </el-form-item>
        </div>

        <!-- 健康信息 -->
        <div class="form-section">
          <h3>健康信息</h3>
          
          <el-form-item label="健康状况">
            <el-checkbox v-model="profileForm.has_diabetes">糖尿病</el-checkbox>
            <el-checkbox v-model="profileForm.has_hypertension">高血压</el-checkbox>
            <el-checkbox v-model="profileForm.has_heart_disease">心脏病</el-checkbox>
          </el-form-item>
        </div>

        <!-- 营养信息显示 -->
        <div class="form-section" v-if="showNutritionInfo">
          <h3>营养建议</h3>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="nutrition-card">
                <h4>基础代谢率(BMR)</h4>
                <div class="nutrition-value">{{ bmrValue || '--' }}</div>
                <div class="nutrition-unit">卡路里/天</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="nutrition-card">
                <h4>每日总消耗(TDEE)</h4>
                <div class="nutrition-value">{{ tdeeValue || '--' }}</div>
                <div class="nutrition-unit">卡路里/天</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="nutrition-card">
                <h4>建议摄入</h4>
                <div class="nutrition-value">{{ calorieTarget || '--' }}</div>
                <div class="nutrition-unit">卡路里/天</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="handleBack" v-if="isFromDetail">返回详情页</el-button>
          <el-button type="primary" @click="saveProfile" :loading="saving">
            保存资料
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="testInputEdit" type="warning">测试输入框编辑</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.user-profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
}

.profile-header h1 {
  color: #303133;
  margin-bottom: 10px;
  font-size: 28px;
}

.profile-header p {
  color: #606266;
  font-size: 16px;
}

.profile-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-section {
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
  border-bottom: none;
}

.form-section h3 {
  color: #303133;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

.bmi-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

.bmi-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.nutrition-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.nutrition-card h4 {
  margin: 0 0 10px 0;
  color: #495057;
  font-size: 14px;
}

.nutrition-value {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 5px;
}

.nutrition-unit {
  font-size: 12px;
  color: #6c757d;
}

.form-actions {
  text-align: center;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  margin: 0 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-profile-container {
    padding: 10px;
  }
  
  .profile-content {
    padding: 20px;
  }
  
  .form-section {
    margin-bottom: 30px;
  }
}

/* 确保输入框可编辑 */
.el-input-number {
  border: 1px solid #dcdfe6 !important;
  border-radius: 4px !important;
  background-color: #ffffff !important;
}

.el-input-number:hover {
  border-color: #c0c4cc !important;
}

.el-input-number:focus-within {
  border-color: #409eff !important;
}

.el-input-number .el-input__inner {
  background-color: #ffffff !important;
  color: #606266 !important;
  cursor: text !important;
}

.el-input-number .el-input__inner:disabled {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}

/* 移除可能的只读样式 */
.el-input-number[readonly] .el-input__inner {
  background-color: #ffffff !important;
  color: #606266 !important;
  cursor: text !important;
}
</style>